﻿using Elves;
using Elves.State;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ElvesController : MonoBehaviour
{
    [SerializeField]
    ElvesBody Elves;

    PlayerStateMachine<ElvesState> stateMachine;

    ElvesState currentState;

    PlayerBody Player;

    Transform enemyTarget;


    [SerializeField] private LayerMask enemyLayer;
    [SerializeField] private Transform playerPos;

    private void Start()
    {
        if (Player == null)
            Elves = transform.GetComponent<ElvesBody>();

        Player = Elves.Player;

        if (stateMachine == null)
            stateMachine = new PlayerStateMachine<ElvesState>();

        stateMachine.AddState(ElvesState.Normal, new ElvesNormal(Elves));
        stateMachine.AddState(ElvesState.Attack, new ElvesAttack(Elves));

        currentState = ElvesState.Normal;
        stateMachine.ChangeState(currentState);
    }


    private void Update()
    {
        Collider2D enemy = AttackCheck();
        if (enemy!=null)
        {
            enemyTarget = enemy.gameObject.transform;
            currentState = ElvesState.Attack;
            stateMachine.ChangeState(currentState);
        }

        switch (currentState)
        {
            case ElvesState.Normal:
                stateMachine.OnUpdate(playerPos);
                break;
            case ElvesState.Attack:
                stateMachine.OnUpdate(enemy);
                break;
            case ElvesState.Protect:
                break;
            case ElvesState.BackToPlayer:
                break;
            case ElvesState.Skill:
                break;
            case ElvesState.PlayerDead:
                break;
            default:
                break;
        }
    }

    private void FixedUpdate()
    {
        if(stateMachine!=null)
            stateMachine.FixedUpdate();
    }

    /// <summary>
    /// 攻击检测
    /// </summary>
    /// <returns>是否有敌人</returns>
    private Collider2D AttackCheck()
    {
        if (Elves.ElvesStatus.isProtect||Elves.ElvesStatus.isSkill)
            return null;
        Collider2D collider = Physics2D.OverlapCircle(Elves.transform.position, Elves.ElvesData.AtkRange, enemyLayer);
        return collider;
    }



    private void ProtectCheck()
    {
        
    }

    private void ReadyToSkill()
    {

    }

    private void BackToPlayer()
    {

    }

}
